package com.lightjet.macross.base.upms.controller;

import com.jayway.jsonpath.internal.filter.ValueNode;
import com.lightjet.macross.base.feign.api.controller.PrincipalController;
import com.lightjet.macross.base.feign.api.domain.AuthUser;
import com.lightjet.macross.base.upms.domain.RoleInfo;
import com.lightjet.macross.base.upms.domain.SystemInfo;
import com.lightjet.macross.base.upms.service.RoleInfoService;
import com.lightjet.macross.base.upms.service.RoleUserLinkService;
import com.lightjet.macross.base.upms.service.SysUserService;
import com.lightjet.macross.base.upms.service.SystemInfoService;
import com.lightjet.macross.common.dto.ResponseDTO;
import com.lightjet.macross.common.util.RespUtil;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.*;
import lombok.extern.java.Log;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Role;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/role")
@Scope("request")
@Log
@RefreshScope
@Api(tags="通用系统权限管理-角色相关接口集")
public class RoleController extends PrincipalController {
    @Resource
    private SysUserService sysUserService;

    @Resource
    private RoleUserLinkService roleUserLinkService;

    @Resource
    private RoleInfoService roleInfoService;

    @Resource
    private SystemInfoService systemInfoService;

    @RequestMapping(value = "/user", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "用户已授权角色查询接口", notes = "根据用户、角色所在系统获取用户角色数据集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name="systemshortname",value = "系统简称",paramType = "query",required = true),
            @ApiImplicitParam(name="userkey",required = false,value = "用户唯一键,如传空值则取Token中的用户信息",paramType = "query"),
            @ApiImplicitParam(name="exchange-token",value = "认证Header头信息（JWT格式）",paramType = "header")
    })
    public ResponseDTO<List<RoleInfo>> GetRolesBySystemShotNameAndUserKey(String systemshortname, String userkey,
                                                      @ApiIgnore @ModelAttribute("CurrentUser") AuthUser user) {
        return RespUtil.CreateOK(roleUserLinkService.FindBySystemShortNameAndUserKey(systemshortname, StringUtil.isNullOrEmpty(userkey)? user.getId(): userkey));
    }

    @GetMapping("/query")
    @ApiOperation(value = "系统角色查询接口", notes = "根据系统简称及父级角色ID（为空查根节点）查询树状结构的角色集合")
    public ResponseDTO<List<RoleInfo>> GetBySystemAndParent(
            @ApiParam(name = "systemshortname", value = "系统简称", required = true) String systemshortname,
            @ApiParam(name = "parentid", value = "父节点ID") Integer parentid)
    {
        SystemInfo systemInfo = systemInfoService.FindByShortname(systemshortname);
        if(systemInfo==null)
        {
            return RespUtil.CreateError("系统【"+systemshortname+"】不存在");
        }
        if(parentid == null)
        {
            return RespUtil.CreateOK(roleInfoService.FindAllByParentAndBelongsystem(null,systemInfo));
        }
        else
        {
            return RespUtil.CreateOK(roleInfoService.FindAllByParentAndBelongsystem(new RoleInfo(parentid),systemInfo));
        }
    }

    @PostMapping(value ="",consumes = "application/json")
    @ApiOperation(value = "角色新增接口", notes = "根据角色实体对象Json新增")
    public ResponseDTO<RoleInfo> CreateRole(
            @ApiParam(name = "roleInfo",value = "角色实体类Json",type="body")@RequestBody RoleInfo roleInfo){
        if(roleInfo.getParent()!=null && roleInfo.getParent().getId() == null)
        {
            roleInfo.setParent(null);
        }
        return RespUtil.CreateOK(roleInfoService.CreateAndFlush(roleInfo));

    }

    @PutMapping(value ="",consumes = "application/json")
    @ApiOperation(value = "角色更新接口", notes = "根据角色实体对象Json更新")
    public ResponseDTO<RoleInfo> UpdateRole(
            @ApiParam(name = "roleInfo",value = "角色实体类Json",type="body")@RequestBody RoleInfo roleInfo){
        RoleInfo original = roleInfoService.FindDistinctById(roleInfo.getId());
        if(original == null)
        {
            return RespUtil.CreateError("更新角色【"+roleInfo.getId()+"】失败");
        }
        else
        {
            original.setRolecode(roleInfo.getRolecode());
            original.setRolename(roleInfo.getRolename());
            original.setRoledescription(roleInfo.getRoledescription());
            original.setEnabled(roleInfo.getEnabled());
            original.setRemark(roleInfo.getRemark());
            return RespUtil.CreateOK(roleInfoService.UpdateAndFlush(original));
        }
    }

    @DeleteMapping(value = "")
    @ApiOperation(value = "角色删除接口", notes = "根据角色ID删除")
    public ResponseDTO<String> DeleteRole( @ApiParam(name = "id",value = "角色ID",type="query") Integer id){
        try {
            roleInfoService.DeleteOne(new RoleInfo(id));
            return RespUtil.CreateOK();
        }
        catch (Exception e)
        {
            return RespUtil.CreateError("删除失败："+e.getMessage());
        }
    }
}
